<?php

namespace App\Http\Middleware;

use Closure;
use EasyWeChat\Foundation\Application;

class VerifyWechat
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $options = [
            'debug' => false,
            'app_id' => env('WECHAT_APP_ID'),
            'secret' => env('WECHAT_SECRET'),
            'token' => env('WECHAT_TOKEN'),
            'aes_key' => env('WECHAT_AES_KEY'),
            'log' => [
                'level' => 'debug',
                'file' => '/tmp/easywechat.log',
            ],
            'oauth' => [
                'scopes' => ['snsapi_userinfo'],
                'callback' => '/callBack',
            ],
        ];

        if ($this->isWeixin()) {
            \Log::debug('授权......');
            $RecommendUser = $request->input('recommend_user');
            if (!empty($RecommendUser)) {
                $request->session()->put('recommend_user', $RecommendUser);
            }
            $app = new Application($options);
            $oauth = $app->oauth;
            return $oauth->redirect();
        }

        return $next($request);
    }

    /**
     * 判断微信客户端
     * @return bool
     */
    public function isWeixin()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }
        return false;
    }
}
